<?php

namespace common\model;

require_once("common/model/User.php");

 class UserDAL {

 	private static $tableName = "users";
 	private $mysqli;

 	public function __construct(\common\model\BaseDAL $baseDAL) {
 		$this->mysqli = $baseDAL->mysqli;
 	}

 	/**
    * @param User user 
    * @throws Exception if something goes wrong.
    */
    public function addUser(\common\model\User $user) {
        $username = $user->username;
        $password = $user->encryptPassword();

        $sql = "INSERT INTO " . self::$tableName . " ( username, password ) VALUES(?, ?)";
        
        $statement = $this->mysqli->prepare($sql);
        if ($statement === false) {
            throw new \Exception("Preparation of $sql statement failed");
        }
        if ($statement->bind_param("ss", $username, $password) === false) {
            throw new \Exception("Binding of $sql failed");
        }
        if ($statement->execute() === false) {
            throw new \Exception("Execution of $sql failed");
        }
    }

    /**   
     * @param  User $users
     * @param  User $input
     * @return bool
     */
    public function userExists($input) {
        $users = $this->getAllUsers();
        foreach ($users as $user) {
            if ($this->compareUsers($user->username, $input->username)) {
                throw new \Exception("User already exsist");
            }
        }
    }

    public function compareUsers($input, $user) {
        if ($input == $user) {
            return true;
        }
    }

    public function findUser($input) { 
       	
    	return $this->getUser($input->username);;
    }

    /**	
     * Returns an array of users from the database
     * @return array users
     */
    public function getAllUsers() {
        $users = array();
        $sql = "SELECT username, password, pk FROM ".self::$tableName.";";

        $statement = $this->mysqli->prepare($sql);
        if ($statement === false) {
            throw new \Exception("Preparation of $sql statement failed");
        }
        if ($statement->execute() === false) {
            throw new \Exception("Execution of $sql statement failed");
        }
        $result = $statement->get_result();
        while ($object = $result->fetch_array(MYSQLI_ASSOC))
        {
            $users[] = new \common\model\User($object["username"], $object["password"], $object["pk"]);
        }
        return $users;
    }

    /**	
     * Returns a user 
     * @return array users
     */
    public function getUser($username) {
        $sql = "SELECT username, password, pk FROM ".self::$tableName." WHERE username ='".$username."';";

        $statement = $this->mysqli->prepare($sql);
        if ($statement === false) {        	
            throw new \Exception("Preparation of $sql statement failed");
        }
        if ($statement->execute() === false) {
            throw new \Exception("Execution of $sql statement failed");
        }
        $result = $statement->get_result();
        $object = $result->fetch_array(MYSQLI_ASSOC);        
        $user = new \common\model\User($object["username"], $object["password"], $object["pk"]);
        
        return $user;
    }

    /** 
     * Returns a user 
     * @return array users
     */
    public function getUserById($userId) {
        $sql = "SELECT username, password, pk FROM ".self::$tableName." WHERE pk ='".$userId."';";

        $statement = $this->mysqli->prepare($sql);
        if ($statement === false) {         
            throw new \Exception("Preparation of $sql statement failed");
        }
        if ($statement->execute() === false) {
            throw new \Exception("Execution of $sql statement failed");
        }
        $result = $statement->get_result();
        $object = $result->fetch_array(MYSQLI_ASSOC);        
        $user = new \common\model\User($object["username"], $object["password"], $object["pk"]);

        if ($user->username == "" || $user->password == "") {
            throw new \Exception("That user does not exist");
        }
        return $user;
    }
 	
 	/**
    * From https://coursepress.lnu.se/kurs/webbutveckling-med-php/exempelsida/mysqli-och-dal/
    * Only run on new system
    */
    public function createUserTable() {
        $sqlStmt = "CREATE TABLE `".self::$tableName."` 
            (
                `pk` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, 
                `username` VARCHAR(255),
                `password` VARCHAR(255)
            )
            ENGINE = innoDB;";
       
      if ($this->mysqli->query($sqlStmt) === false) {
          throw new \Exception("'$sqlStmt' failed ");
      }
    }
}